# -*- coding: utf-8 -*-
# @Time    : 2022/6/26 17:25
# @Author  : 我还能卷
# @FileName: apis.py
# @Software: PyCharm
import re

import jsonpath
import requests
from faker import Faker


class ApiCases:
    @classmethod
    def replace_data(cls, my_string):
        """替换 #。。# 标记"""
        result = re.finditer('#(.+?)#', my_string)
        for el in result:
            target = el.group()  # #smsflag#
            prop = el.group(1)  #
            value = getattr(cls, prop)
            my_string = my_string.replace(target, value)
        return my_string

    def send_sms(self, mobile):
        """发送验证码"""
        response = requests.get(url='http://47.115.15.198:7001/smarthome/verificationCode/message',
                                params={"phone": mobile})
        code = response.json()['data']
        return code

    def register(self, pswd='abcd1234'):
        """注册账号"""
        # 随机生成中国地区数据
        fk = Faker(locale=['zh-CN'])

        # 生成手机号码
        phone = fk.phone_number()
        users_name = fk.pystr(min_chars=4, max_chars=6)
        data = {

            "phone": phone,

            "pwd": pswd,

            "rePwd": pswd,

            "userName": users_name,

            "verificationCode": "lemon"

        }
        headers = {
            "X-Lemonban-Media-Type": "lemonban.v2",
            "content-type": "application/json"
        }
        response = requests.post(url='http://47.115.15.198:7001/smarthome/user/register',
                                 headers=headers, json=data)
        # content = response.json()
        # userid = jsonpath.jsonpath(content, '$..id')[0]
        return users_name, pswd

    def login(self, uesr_name, password):
        """登录"""
        headers = {
            "X-Lemonban-Media-Type": "lemonban.v2",
            "content-type": "application/json"
        }
        data = {
            "pwd": password,
            "userName": uesr_name
        }
        response = requests.post(url='http://47.115.15.198:7001/smarthome/user/login',
                                 headers=headers, json=data)
        content = response.json()
        userid = jsonpath.jsonpath(content, '$..id')[0]
        token_type = jsonpath.jsonpath(content, '$..token_type')[0]
        tokens = jsonpath.jsonpath(content, '$..token')[0]
        authorization = token_type + ' ' + tokens
        return userid, authorization

    def set_merchant(self, userid, token, merchantType):
        """通过faker随机生成所需信息
        merchantType=2代表代理商，=3代表物业"""
        fk = Faker(locale="zh-CN")
        data = {

            "address": fk.address(),

            "establishDate": str(fk.date()),

            "legalPerson": fk.name(),

            "licenseCode": fk.ssn(),

            "licenseUrl": "http://127.0.0.1/smarthome/sxc.jpg",

            "merchantName": fk.company(),

            "merchantType": merchantType,

            "registerAuthority": "sxcvknfybnvucdfryewoghfngbteg",

            "tel": fk.phone_number(),

            "userId": userid,

            "validityDate": str(fk.future_date())

        }
        headers = {
            "content-type": "application/json",

            "Authorization": token,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        response = requests.put(headers=headers,
                                url='http://47.115.15.198:7001/smarthome/merchant/complete',
                                json=data,
                                )
        content = response.json()
        return userid, token

    def add_community(self, userid, token):
        """通过faker随机生成所需信息"""
        fk = Faker(locale="zh-CN")
        headers = {
            "content-type": "application/json",

            "Authorization": token,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        data = {
            "address": fk.address(),
            "communityName": '乐天大花园',
            "nearbyLandmarks": fk.street_name(),
            "userId": userid
        }
        response = requests.post(headers=headers,
                                 url='http://47.115.15.198:7001/smarthome/community/add',
                                 json=data,
                                 )
        content = response.json()
        communityId = jsonpath.jsonpath(content, '$..communityId')[0]
        return communityId

    def community_examine(self, communityid, state):
        """通过faker随机生成所需信息
        小区审核，communityId代表小区id，state代表审核结果"""
        fk = Faker(locale="zh-CN")
        login_headers = {
            "X-Lemonban-Media-Type": "lemonban.v2",
            "content-type": "application/json"
        }
        login_data = {
            "pwd": '1234567a',
            "userName": 'admin'
        }
        login_response = requests.post(url='http://47.115.15.198:7001/smarthome/user/login',
                                       headers=login_headers, json=login_data)
        login_content = login_response.json()
        tokens = jsonpath.jsonpath(login_content, '$..token')[0]
        authorization = 'Bearer ' + tokens

        headers = {
            "content-type": "application/json",

            "Authorization": authorization,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        data = {
            "communityId": communityid,
            "remark": fk.sentence(),
            "state": state
        }
        response = requests.post(headers=headers,
                                 url='http://47.115.15.198:7001/smarthome/community/examine',
                                 json=data,
                                 )
        content = response.text

    def community_in(self, communityid, userid, token):
        """通过faker随机生成所需信息
        小区入住，communityId代表小区id，user需要位物业"""
        headers = {

            "Authorization": token,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        params = {'communityId': communityid, 'userId': userid}
        response = requests.post(headers=headers,
                                 url='http://47.115.15.198:7001/smarthome/community/in',
                                 params=params
                                 )

        commumeberid = jsonpath.jsonpath(response.json(), '$..commuMemberId')[0]
        return commumeberid

    def community_in_examine(self, commumenberid, state, token):
        """通过faker随机生成所需信息
        小区入驻审核审核，commumenberid代表小区成员id，state代表审核结果"""
        fk = Faker(locale="zh-CN")
        headers = {
            "content-type": "application/json",
            "Authorization": token,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        data = {
            "commuMemberId": commumenberid,
            "remark": fk.paragraph(),
            "state": state
        }
        response = requests.post(headers=headers,
                                 url='http://47.115.15.198:7001/smarthome/community/in/examine',
                                 json=data
                                 )

    def building_add(self, userid, token, communityid):
        """通过faker随机生成所需信息
                小区入驻审核审核，communityId代表小区id，state代表审核结果"""
        fk = Faker(locale="zh-CN")
        headers = {
            "content-type": "application/json",
            "Authorization": token,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        data = {
            "buildingName": fk.word(),
            "buildingNum": fk.random_int(),
            "communityId": communityid,
            "floorage": fk.numerify(),
            "remark": fk.paragraph(),
            "userId": userid
        }
        response = requests.post(headers=headers,
                                 url='http://47.115.15.198:7001/smarthome/building/add',
                                 json=data
                                 )
        buildingId = jsonpath.jsonpath(response.json(), '$..buildingId')[0]
        return buildingId

    def building_unit(self, userid, token, buildingId, lift):
        """通过faker随机生成所需信息
                        小区入驻审核审核，buildingId代表楼栋id"""
        fk = Faker(locale="zh-CN")
        headers = {
            "content-type": "application/json",
            "Authorization": token,

            "X-Lemonban-Media-Type": "lemonban.v2"

        }
        data = {
            "buildingId": buildingId,
            "floorage": fk.random_number(digits=3),
            "layerCount": fk.random_number(digits=2),
            "lift": lift,
            "remark": fk.paragraph(),
            "unitNum": fk.random_int(max=20),
            "userId": userid
        }
        response = requests.post(headers=headers,
                                 url='http://47.115.15.198:7001/smarthome/unit/add',
                                 json=data
                                 )
        print(response.text)


if __name__ == '__main__':
    ca = ApiCases()
    user_name1, pwd1 = ca.register()
    id1, token1 = ca.login(user_name1, pwd1)
    user_name2, pwd2 = ca.register()
    id2, token2 = ca.login(user_name2, pwd2)
    agent_id, agent_token = ca.set_merchant(id1, token1, 2)
    prop_id, prop_token = ca.set_merchant(id2, token2, 3)
    comun_id = ca.add_community(id1, token1)
    ca.community_examine(comun_id, 1)
    commumeberid = ca.community_in(comun_id, id2, token2)
    ca.community_in_examine(commumeberid, 1, token1)
    buildingId = ca.building_add(id2, token2, comun_id)
    print(buildingId)
    ca.building_unit(id2, token2, buildingId, 1)
